using System;
using System.Data;
using System.Data.OleDb;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using Forecast.Database;
using Forecast.Business;

public partial class controls_forms_NewsForm : System.Web.UI.UserControl
{
    public SaveComplete OnSaveComplete = null;
    private const string NOT_LINKED = "Not linked";

    public int NewsId
    {
        get
        {
            if (ViewState["NewsId"] != null)
                return Convert.ToInt32(ViewState["NewsId"]);
            else
                return 0;
        }
        set
        {
            ViewState["NewsId"] = value;
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            ToggleCreateMode(true);
        }        
    }

    private void ResetForm()
    {
        ToggleCreateMode(true);
        _title.Text = "";
        _message.Text = "";
        NewsId = 0;
    }

    private void ToggleCreateMode(bool newArticle)
    {
        _create.Visible = newArticle;
        _update.Visible = !newArticle;
        _delete.Visible = !newArticle;
        _cancel.Visible = !newArticle;

        if (newArticle)
        {
            _predictionList.Visible = true;
            _predictionListLabel.Visible = true;

            Activity activity = new Activity(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
            DataTable activePredictions = activity.GetActivePredictions();
            DataRow row = activePredictions.NewRow();
            row[ActivePredictions.Columns.Ticker.ToString()] = NOT_LINKED;
            row[ActivePredictions.Columns.PredictionId.ToString()] = -1;
            activePredictions.Rows.Add(row);

            _predictionList.DataSource = activePredictions;
            _predictionList.DataTextField = ActivePredictions.Columns.Ticker.ToString();
            _predictionList.DataValueField = ActivePredictions.Columns.PredictionId.ToString();
            _predictionList.DataBind();
            _predictionList.SelectedIndex = activePredictions.Rows.Count - 1;
        }
        else
        {
            _predictionList.Visible = false;
            _predictionListLabel.Visible = false;
        }
    }

    public void LoadNewsArticle(Int32 newsId)
    {
        string sql = "SELECT * FROM [NewsItem] WHERE ID = ?";
        OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        cn.Open();
        OleDbCommand cm = new OleDbCommand(sql, cn);
        cm.Parameters.Add("ID", OleDbType.Integer).Value = newsId;
        try
        {
            OleDbDataReader reader = cm.ExecuteReader();

            while (reader.Read())
            {
                _title.Text = reader["Title"].ToString();
                _message.Text = reader["News_message"].ToString();
            }
            reader.Close();
        }
        finally
        {
            cn.Close();
        }

        NewsId = newsId;

        ToggleCreateMode(false);
    }

    protected void _create_Click(object sender, EventArgs e)
    {
        string sql = "INSERT INTO [NewsItem] ([Title], [News_message], [News_date], [Prediction_id], [Player_id]) VALUES (?,?,?,?,?)";
        
        OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        cn.Open();
        OleDbCommand cm = new OleDbCommand(sql, cn);
        cm.Parameters.Add("Title", OleDbType.VarWChar).Value = _title.Text;
        cm.Parameters.Add("News_message", OleDbType.VarWChar).Value = _message.Text;
        cm.Parameters.Add("News_date", OleDbType.Date).Value = DateTime.Now;
        if (_predictionList.SelectedItem.Text != NOT_LINKED)
            cm.Parameters.Add("Prediction_id", OleDbType.Integer).Value = Int32.Parse(_predictionList.SelectedItem.Value); 
        else
            cm.Parameters.Add("Prediction_id", OleDbType.Integer).Value = DBNull.Value;
        cm.Parameters.Add("Player_id", OleDbType.Integer).Value = DBNull.Value; // Will not be linked yet
        try
        {
            int result = cm.ExecuteNonQuery();
        }
        finally
        {
            cn.Close();
        }

        ResetForm();

        if (OnSaveComplete != null)
            OnSaveComplete();
    }

    protected void _update_Click(object sender, EventArgs e)
    {
        Load load = new Load(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        NewsItem newsItem = load.GetNewsItem(NewsId);
        newsItem.Message = _message.Text;
        newsItem.PlayerId = newsItem.PlayerId;
        newsItem.PredictionId = newsItem.PredictionId; 
        newsItem.Title = _title.Text;
        Save save = new Save(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        save.EditNewsItem(newsItem);       

        ResetForm();

        if (OnSaveComplete != null)
            OnSaveComplete();
    }

    protected void _delete_Click(object sender, EventArgs e)
    {
        string sql = "DELETE FROM [NewsItem] WHERE ID = ?";

        OleDbConnection cn = new OleDbConnection(ConfigurationManager.ConnectionStrings["ForecastDB"].ConnectionString);
        cn.Open();
        OleDbCommand cm = new OleDbCommand(sql, cn);
        cm.Parameters.Add("ID", OleDbType.Integer).Value = NewsId;
        try
        {
            int result = cm.ExecuteNonQuery();
        }
        finally
        {
            cn.Close();
        }

        ResetForm();

        if (OnSaveComplete != null)
            OnSaveComplete();
    }

    protected void _cancel_Click(object sender, EventArgs e)
    {
        ResetForm();
    }
}
